package com.lkx.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * ClassName: ServiceAspect
 * Function:  TODO
 * Date:      2019-10-31 12:41
 * author     likaixuan
 * version    V1.0
 */
@Component
@Aspect
public class ServiceAspect {

    private static Logger log = LoggerFactory.getLogger(ServiceAspect.class);


    // Service层切点
    //@Pointcut("execution(* com.lkx.service.*Service.*(..))")
    @Pointcut("execution(* com.lkx.web.*Controller.*(..))")
    public void servicePointCut() {

    }

    @Before("servicePointCut()")
    public void doBefore(final JoinPoint jp) {
        Class<?> targetClass = jp.getTarget().getClass();
        if (log.isDebugEnabled()) {
            String methodName = jp.getSignature().getName();
            log.debug("Service Begining method: " + targetClass.getName() + "." + methodName);
        }
    }

    @Around("servicePointCut()")
    public Object doAround(final ProceedingJoinPoint pjp) throws Throwable {
        Class<?> targetClass = pjp.getTarget().getClass();

        long time = System.currentTimeMillis();

        Object retVal = pjp.proceed();

        if (log.isDebugEnabled()) {
            time = System.currentTimeMillis() - time;
            log.debug("process time: " + time + " ms");
        }

        return retVal;
    }

    @After("servicePointCut()")
    public void doAfter(final JoinPoint jp) {
        Class<?> targetClass = jp.getTarget().getClass();
        if (log.isDebugEnabled()) {
            String methodName = jp.getSignature().getName();
            log.debug("Service Ending method: " + targetClass.getName() + "." + methodName);
        }
    }

    @AfterThrowing(value = "servicePointCut()", throwing = "ex")
    public void doThrowing(final JoinPoint jp, final Throwable ex) {
        Class<?> targetClass = jp.getTarget().getClass();
        log.error(ex.getMessage(), ex);
    }
}
